package com.autumn.repo.service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.InitializingBean;

import com.autumn.repo.Repo;
import com.autumn.repo.RepoFilter;
import com.autumn.repo.RepoService;
import com.autumn.repo.meta.RepoImpl;

public abstract class AbstractRepoService implements RepoService, InitializingBean {

    private String root;

    public String getRoot() {
        return root;
    }

    public void setRoot(String root) {
        this.root = root;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        File file = new File(root);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    @Override
    public List<Repo> list(RepoFilter filter) {
        File[] files = this.filterRepoPath(new File(root));
        List<Repo> repos = new ArrayList<>();
        if (null != files) {
            for (File path : files) {
                Repo repo = this.convertPath2Repo(root, path);
                if (null == filter || filter.accept(repo)) {
                    repos.add(repo);
                }
            }
        }
        return repos;
    }

    abstract protected File[] filterRepoPath(File root);

    private Repo convertPath2Repo(String root, File path) {
        RepoImpl repo = new RepoImpl();
        repo.setName(path.getName());
        return repo;
    }
}
